<template>
    <div class="container">
        <div class="header">
          <header-bar></header-bar>
        </div>
        <div class="saveContainer">
            <el-row  :gutter="20">
                <el-col :span="6" >
                    <p @click="back">{{ $t('home.nav') }} > {{ type==="text"?$t('home.text'):$t('home.article') }}</p>
                </el-col>
                <el-col :span="4" :offset="13">
                    <div class="btnContainer">
                        <el-button type="primary" size="small" @click="save">{{ $t('home.save') }}</el-button>
                        <el-button type="primary" size="small" @click="prev">{{ $t('home.prev') }}</el-button>
                    </div>
                </el-col>
            </el-row>
        </div>
        <div class="editContainer">
          <div class="row">
            <div class="articleUpload">
              <el-upload
                  class="upload-cover"
                  list-type="picture-card"
                  action="https://course.acktechnologies.com.cn/api/card/upload"
                  :on-progress="progress"
                  :on-success="uploadOk"
                  :on-error="uploadErro"
                  :on-change="fileChange"
                  :show-file-list="false"
                  :data="uploaddata"
                  v-show="!fileFlag"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div class="coverImg"
                     @mouseleave="coverHover = false"
                     @mouseenter="coverHover = true"
                     v-show="coverImg">
                  <img
                      class="el-upload-list__item-thumbnail"
                      :src="coverImg"
                      alt=""
                  />
                  <div class="oprateContainer" v-show="coverHover">
                    <div class="replace">
                      {{$t('home.replace')}}
                    </div>
                    <div class="remove" @click.stop="remove">
                      {{$t('home.delete')}}
                    </div>
                  </div>
                </div>
              </el-upload>
              <el-progress type="circle"
                           :percentage="progressVal"
                           v-show="fileFlag">
              </el-progress>
            </div>
            <div class="content">
              <el-row>
                <el-col :span="24">
                  <el-input v-model="title" :placeholder="$t('home.enterTitle')"></el-input>
                </el-col>
                <el-col :span="24" style="margin-bottom: 10px">
                  <div class="desc">
                    <el-input
                        type="textarea"
                        :placeholder="$t('home.enterText')"
                        v-model="textarea"
                        maxlength="200"
                        show-word-limit
                        style="height: 100px"
                    >
                    </el-input>
                  </div>
                </el-col>
                <el-col :span="8">
                  <el-select v-model="value" :placeholder="$t('home.SelectCategories')">
                    <el-option
                        v-for="item in options"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="15" :offset="1">
                  <el-select v-model="templatesValue" :placeholder="$t('home.PleaseSelectTemplate')">
                    <el-option
                        v-for="item in templates"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="24" style="margin-top: 10px">
                  <el-input v-model="tag" :placeholder="$t('home.tag')"></el-input>
                  <p style="text-align: left;color: #d71010">添加多个标签请用，号分开</p>
                </el-col>
              </el-row>
            </div>
          </div>
            <div class="editorContent">
              <div class="editorLeft">
                <el-upload
                    class="upload-article"
                    list-type="picture-card"
                    action="https://course.acktechnologies.com.cn/api/card/upload"
                    :on-progress="progress"
                    :on-success="articleUploadOk"
                    :on-error="uploadErro"
                    :on-change="articlefileChange"
                    :show-file-list="false"
                    :data="uploaddata"
                    v-show="!fileFlag1"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div class="coverImg"
                       @mouseleave="articleHover = false"
                       @mouseenter="articleHover = true"
                       v-show="articleImg">
                    <img
                        class="el-upload-list__item-thumbnail"
                        :src="articleImg"
                        alt=""
                    />
                    <div class="oprateContainer" v-show="articleHover">
                      <div class="replace">
                        {{ $t('home.replace') }}
                      </div>
                      <div class="remove" @click.stop="articleremove">
                        {{ $t('home.delete') }}
                      </div>
                    </div>
                  </div>
                </el-upload>
                <el-progress type="circle"
                             :percentage="progressVal"
                             v-show="fileFlag1">
                </el-progress>
              </div>
              <div>
                <div id="editor"></div>
              </div>
            </div>
        </div>
        <el-dialog :title="$t('home.prev')"
        width="414px"
        height="734px"
        custom-class="prevContainer"
        :visible.sync="previewFlag">
            <p class="title">{{title}}</p>
            <div class="picture">
                <img :src="articleImg" alt="">
            </div>
            <div class="content" v-html="editorData"></div>
        </el-dialog>
    </div>
</template>
<script>

import { get,post} from "../assets/js/http";
import headerBar from "@/components/header"
import E from 'wangeditor'
export default {
    name:'article_editor',
    data(){
        return{
            loginout:false,
            avatar: this.$cookies.get("avatar"),
            nickname: this.$cookies.get("nickname"),
            coverImg:sessionStorage.getItem('cover'),
            uploaddata:{
                token: this.$cookies.get("vtrstoken")
            },
            fileFlag:false, //封面上传
            fileFlag1:false, //正文图片上传
            progressVal:0,
            title:"",
            value:"",
            options:"",
            textarea:"",
            editor: null,
            editorData: '',
            articleImg:sessionStorage.getItem('cover'),
            coverHover:false,
            articleHover:false,
            templates:"",
            templatesValue:"",
            type:this.$route.query.id,
            previewFlag:false,
            tag:'',
        }
    },
    components:{
      headerBar
    },
    created() {
        this.getOption();
        this.getTemplates();
        if (this.$route.query.editor){
            this.view();
        }
    },
    mounted(){
        const editor = new E('#editor');
        editor.config.height = 129;
        editor.config.zIndex = 1;
        editor.config.menus = [
            'head',
            'bold',
            'fontSize',
            'fontName',
            'italic',
            'underline',
            'strikeThrough',
            'indent',
            'lineHeight',
            'foreColor',
            'backColor',
            'link',
            'list',
            'todo',
            'justify',
            'quote',
            'emoticon',
            'splitLine',
            'undo',
            'redo',
        ];
        // 配置 onchange 回调函数，将数据同步到 vue 中
        editor.config.onchange = (newHtml) => {
            this.editorData = newHtml
        };
        editor.create();
        this.editor = editor;
    },
    beforeDestroy() {
        // 调用销毁 API 对当前编辑器实例进行销毁
        this.editor.destroy();
        this.editor = null
    },
    methods:{
        back(){
                this.$router.back(-1);
            },
        view(){
            get("https://course.acktechnologies.com.cn/api/card/preview", {
                token: this.$cookies.get("vtrstoken"),
                id:this.$route.query.editor
            }).then(res => {
                if (res.code === 1) {
                    let info = res.data;
                    this.title = info.title;
                    this.textarea = info.description;
                    if (info.tag.length){
                      for (let i=0;i<info.tag.length;i++){
                        if (i===(info.tag.length-1)){
                          this.tag += info.tag[i].name;
                        }else {
                          this.tag += info.tag[i].name+",";
                        }

                      }
                    }
                    this.articleImg = info.kapian.article_image;
                    this.editor.txt.html(info.kapian.content);
                    this.coverImg = info.image;
                    this.value = info.user_category_id;
                    this.templatesValue = info.kapian.template.id;
                } else {
                    this.$message({
                        message: res.msg,
                        type: "warning"
                    });
                }
            })
                .catch(error => {
                    // error
                    this.$message({
                        message: error.msg,
                        type: "warning"
                    });
                    console.log(error);
                });
        },
        save(){
            let param = new FormData();
            param.append("token",this.$cookies.get("vtrstoken"));

            if (this.value){
                param.append("user_category_id",this.value);
            }else {
                param.append("user_category_id",0);
            }
            if (this.templatesValue){
                param.append("template",this.templatesValue);
            }else{
                this.$message({
                    message:"请选择模板！",
                    type: "warning"
                });
                return false;
            }
            if (this.title){
                param.append("title",this.title);
            }else{
                this.$message({
                    message:"请填写标题！",
                    type: "warning"
                });
                return false;
            }
            if (this.textarea){
                param.append("description",this.textarea);
            }else{
                this.$message({
                    message:"请填写描述！",
                    type: "warning"
                });
                return false;
            }
            if (this.textarea){
                param.append("content",this.editor.txt.html());
            }else{
                this.$message({
                    message:"请填写正文内容！",
                    type: "warning"
                });
                return false;
            }
            if (this.coverImg){
                param.append("image",this.coverImg);
            }
            if (this.tag){
              param.append("tag",this.tag);
            }
            param.append("article_image",this.articleImg);
            let serveUrl = "";
            if (this.$route.query.editor){
                param.append("id",this.$route.query.editor);
                param.append("tag",this.tag);
                serveUrl = 'https://course.acktechnologies.com.cn/api/card/edit';
            }else{
                param.append("type",this.type);
                serveUrl = 'https://course.acktechnologies.com.cn/api/card/add'
            }
            post(serveUrl, param).then(res => {
                if (res.code===1){
                    this.$message({
                        message: res.msg,
                        type: "success"
                    });
                    setTimeout(()=>{
                        this.$router.push({path:'./'})
                    },2000)
                }
            })
                .catch(error => {
                    // error
                    this.$message({
                        message: error.msg,
                        type: "warning"
                    });
                    console.log(error);
                });
        },
        prev(){
            this.previewFlag = true;
        },
        articleremove(){
            this.articleImg = "";
        },
        remove(){
            this.coverImg = "";
        },
        getEditorData() {
            // 通过代码获取编辑器内容
            let data = this.editor.txt.html();
            alert(data)
        },
        articleUploadOk(response){
            this.articleImg = response.data.url;
            this.$message({
                message: "上传成功！",
                type: "success"
            });
        },
        uploadOk(response) {
            this.coverImg = response.data.url;
            this.$message({
                message: "上传成功！",
                type: "success"
            });
        },
        uploadErro() {
            this.$confirm("图片上传失败", "", {
                confirmButtonText: "确定",
                showCancelButton: false,
                confirmButtonClass: "sureBtn",
                type: "warning",
                center: true
            })
            .then(() => {})
            .catch(() => {});
        },
        articlefileChange(file){
            if (file.status == "ready") {
                this.fileFlag1 = true;
            } else {
                this.fileFlag1 = false;
            }
        },
        fileChange(file) {
            console.log(file);
        if (file.status == "ready") {
            this.fileFlag = true;
        } else {
            this.fileFlag = false;
        }
            console.log(this.fileFlag);
        },
        progress(event) {
            this.progressVal = parseInt(event.percent);
        },
        getOption(){
            get("https://course.acktechnologies.com.cn/api/card/categories", {
                token: this.$cookies.get("vtrstoken"),
                currentpage:1,
                pagesize:50
            }).then(res => {
                if (res.code === 1) {
                    this.options = res.data.list;
                } else {
                    this.$message({
                        message: res.msg,
                        type: "warning"
                    });
                    }
                })
                .catch(error => {
                    // error
                    this.$message({
                    message: error.msg,
                    type: "warning"
                    });
                    console.log(error);
                });
        },
        getTemplates(){
            get("https://course.acktechnologies.com.cn/api/card/templates", {
                token: this.$cookies.get("vtrstoken"),
                type:this.$route.query.id
            }).then(res => {
                    if (res.code === 1) {
                    this.templates = res.data;
                    this.templates.map((item)=>{
                        if (item.id==this.$route.query.temp){
                            this.templatesValue = item.name;
                        }
                    })
                    } else {
                    this.$message({
                        message: res.msg,
                        type: "warning"
                    });
                    }
                })
                .catch(error => {
                    // error
                    this.$message({
                    message: error.msg,
                    type: "warning"
                    });
                    console.log(error);
                });
        },
        loginoutHadle() {
      get("https://course.acktechnologies.com.cn/api/user/logout", {
        token: this.$cookies.get("vtrstoken")
      })
          .then(res => {
            if (res.code === 1) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.$cookies.remove("vtrstoken");
              this.$router.push("./login");
            } else {
              this.$message({
                message: res.msg,
                type: "warning"
              });
            }
          })
          .catch(error => {
            // error
            this.$message({
              message: error.msg,
              type: "warning"
            });
            console.log(error);
          });
    },
    }

}
</script>
<style scoped lang="less">
 /deep/ .el-dialog__body{
    padding: 0;
}
     /deep/ .upload-cover,.upload-article{
        text-align: right;
    }
    /deep/ .upload-article{
        margin-right: 20px;
        width: 140px;
      height: 169px;
    }
    /deep/ .upload-cover .el-upload--picture-card{
        width: 200px;
        height: 250px;
        line-height: 250px;
        position: relative;
    }
    /deep/ .upload-article .el-upload--picture-card{
      width: 140px;
      height: 169px;
        position: relative;
    }
 /deep/ .prevContainer .el-dialog__body {
   text-align: left;
   padding: 0;
   margin: 0;
   height: 736px !important;
 }
</style>
<style scoped lang="less">
/deep/ textarea{
  height: 100%;
}
/deep/ .el-select{
  width: 100%;
}
.editorContent{
  display: flex;
  flex-direction: row;
  height: 189px;
  background: #FFFFFF;
  border-radius: 8px;
  border: 1px solid #D5D5D5;
  padding: 10px;
  box-sizing: border-box;
  .editorLeft{
    width: 140px;
    margin-right: 10px;
  }
}
.prevContainer{
    height: 734px;
    overflow-y: auto;
    padding-bottom: 10px;
    .title{
        font-size: 17px;
        font-family: SourceHanSansCN-Regular, SourceHanSansCN;
        color: #333333;
        line-height: 24px;
    }
    .picture{
        width: 100%;
        img{
            display: block;
            width: 100%;
            height: auto;
        }
    }
}
    #editor{
        text-align: left;
      width: 968px;
    }
    .coverImg{
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        img{
            display: block;
            width: 100%;
            height: 100%;
        }
    }
    .oprateContainer{
        position: absolute;
        top: 0;
        left: 0;
        z-index: 9;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 4px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        div{
            width: 134px;
            height: 26px;
            line-height: 26px;
            margin: 0 auto;
            border-radius: 2px;
            border: 1px solid #FFFFFF;
            font-size: 14px;
            font-family: SourceHanSansCN-Normal, SourceHanSansCN;
            font-weight: 400;
            color: #FFFFFF;
        }
        .remove{
            margin-top: 10px;
        }
    }
.container{
    width: 100%;
    height: 100%;
    margin: 0 auto;
    background: #F7F8F8;
    .header{
        height: 60px;
        background: #FFFFFF;
        border-radius: 2px;
        .title {
            height: 60px;
            font-size: 26px;
            font-family: SourceHanSansCN-Medium, SourceHanSansCN;
            font-weight: 500;
            color: #333333;
            line-height: 60px;
            letter-spacing: 3px;
            text-align: center;
            flex-grow: 1;
        }
        .infoContainer{
            display: flex;
            flex-direction: row;
            align-items: center;
            margin-top: 5px;
        }
        .avatar {
            width: 50px;
            height: 50px;
            background: #f2f2f2;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
            border-radius: 50%;
            margin-right: 10px;
            position: relative;
            overflow: hidden;
            img {
                display: block;
                width: 40px;
                height: 40px;
            }
            }
        .nickname {
            font-size: 18px;
            font-family: SourceHanSansCN-Normal, SourceHanSansCN;
            font-weight: 400;
            color: #333333;
            line-height: 24px;
            letter-spacing: 1px;
            position: relative;
        .loginout {
            position: absolute;
            bottom: -43px;
            width: 80px;
            height: 43px;
            line-height: 43px;
            font-size: 14px;
            font-family: SourceHanSansCN-Regular, SourceHanSansCN;
            font-weight: 400;
            color: #666666;
            background: url("../assets/img/loginout.png") no-repeat center
            center/100%;
            box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.21);
            cursor: pointer;
        }
        }
        .downIcon {
            width: 0;
            height: 0;
            border-right: 10px solid transparent;
            border-left: 10px solid transparent;
            border-top: 10px solid #d7d7d7;
            margin-left: 10px;
        }
    }
    .saveContainer{
        width: 1200px;
        margin: 10px auto;
        height: 60px;
        background: #FFFFFF;
        padding-left: 20px;
        p{
            height: 60px;
            line-height: 60px;
            font-size: 18px;
            font-family: SourceHanSansCN-Medium, SourceHanSansCN;
            font-weight: 500;
            color: #666666;
            text-align: left;
            cursor: pointer;
            padding-left: 20px;
        }
        .btnContainer{
            margin-top: 14px;
        }
    }
    .editContainer{
        width: 1200px;
        margin: 10px auto 0 auto;
        background-color: #FFFFFF;
        padding: 20px;
        box-sizing: border-box;
        .editorContent{
            margin-top: 20px;
            padding: 10px;
        }
      .row{
        display: flex;
        flex-direction: row;
        .articleUpload{
          width: 210px;
          height: 220px;
          margin-right: 20px;
        }
        .content{
          width: 910px;
        }
      }
    }
    .desc{
        margin-top: 10px;
    }
}
</style>